package com.liaogui.framework.register;

import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;
import com.google.gson.Gson;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author liaogui
 * @date 2025/4/17 16:51
 */
public class RedisClient {
    public static final String REGISTER_SERVICES = "registerServices";
    private Jedis jedis;

    public RedisClient(String host, int port, String password, int database) {
        this.jedis = new Jedis(host, port);
        jedis.auth(password);
        jedis.select(database);
        String respone = jedis.ping();
        System.out.println("Connected to Redis: " +  respone);
    }

    public void registerService(String serviceName, String serviceAddress) {
        // 先检查是否存在数据
        String result = jedis.hget(REGISTER_SERVICES, serviceName);
        Gson gson = new Gson();
        if (StringUtils.isNotBlank(result)) {
            List list = gson.fromJson(result, List.class);
            list.add(serviceAddress);
            jedis.hset(REGISTER_SERVICES, serviceName, gson.toJson(list));
            return;
        }

        // 使用 HSET 将服务信息存储在 Redis 中
        jedis.hset(REGISTER_SERVICES, serviceName, gson.toJson(Arrays.asList(serviceAddress)));
    }

    public void unregisterService(String serviceName) {
        // 从 Redis 中删除服务信息
        jedis.hdel(REGISTER_SERVICES, serviceName);
    }

    public String discoverService(String serviceName) {
        // 从 Redis 中获取服务地址
        return jedis.hget(REGISTER_SERVICES, serviceName);
    }


}
